/*
* @Author: 17720
* @Date:   2022-08-11 11:43:51
* @Last Modified by:   17720
* @Last Modified time: 2022-08-16 11:09:05
*/

var ini = require('ini');

var fs = require('fs');

var Des = require('./Des.js');

var Res = require('./rsa.js');

const axios = require('axios');

var configinfo = [];

function readConfig(indexkey){
     if(configinfo.length == 0){
       var str = fs.readFileSync(__dirname + "\\config.ini").toString();
     	// 2.使用ini.parse()方法进行转换
	    configinfo = ini.parse(str);
     }
	return configinfo[indexkey]+'';
}
function replacer(key, value) {
  if (typeof value === "string") return undefined;
  return value;
}
function getReqId(){
	return  Date.now() +''+ Math.round(Math.random()*80+20) + Math.round(Math.random()*80+20);
}

 function handleResponse(responseMessage) {
   if(responseMessage['resCode'] != '0000'){
       return false ;
    }
    let verstatus = Res.verify(responseMessage['resData'],responseMessage['sign'],readConfig('YOU_FU_PUBLIC_KEY'));
    if(!verstatus){
      console.log("验签失败!");
      return false;
    }
    console.log('验签成功')
        /** DES 解密 **/
    let reqData =  Des.decrypt( responseMessage['resData'],readConfig('INTER_KEY'));
   if(reqData == '' || reqData == false){
            console.log('解密失败')
           return false;
    }
    console.log('解密成功')
    return JSON.parse(reqData);

 }
module.exports.buildRequest = function(funCodeEnum,reqData){
    let requestMessage = {};
    requestMessage['reqId'] = getReqId();
    requestMessage['merId'] =  readConfig('MER_ID');
    requestMessage['version'] = readConfig('API_VERSION');
    requestMessage['funCode'] = funCodeEnum;
    let jsonReq = JSON.stringify(reqData,replacer());
    let bs =  Des.encrypt( jsonReq , readConfig('INTER_KEY'));
    requestMessage['reqData'] = bs;
    let sign =  Res.getSign(bs, readConfig('MER_PRIVATE_KEY'));
    requestMessage['sign'] = sign;
    console.log('构建请求报文');
    console.log(requestMessage);
    return requestMessage;

}


module.exports.sendToYouFu = function(reqData){
 return axios({
    method:'post',
    url:readConfig('YOU_FU_URL'),
    data:JSON.stringify(reqData,replacer()),
    headers:{
        "Content-Type": "application/json; charset=utf-8",
        'Content-Length': JSON.stringify(reqData,replacer()).length
    }
})
.then(res => {   
    console.log('优付响应 ：');
    console.log(res['data']);
    if(res['status'] == 200){

          return handleResponse(res['data']);
        }else{
            return false;
        }
    })
.catch(err => console.error(err) )};
